<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="fromLogin.mobile"
        label="手机号码"
        placeholder="手机号"
        :rules="[
          {
            required: true,
            message: '请输入正确格式的手机号',
            trigger: 'onChange',
            pattern: /^1[3-9]\d{0,9}$/,
          },
        ]"
      />
      <van-field
        v-model="fromLogin.code"
        type="password"
        label="密码"
        placeholder="密码"
        :rules="[
          {
            required: true,
            message: '请填写密码',
            trigger: 'onChange',
            pattern: /^\d{6}$/,
          },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          :loading="isLoading"
          type="info"
          :disabled="isLoading"
          loading-text="加载中..."
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { Notify } from 'vant'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      fromLogin: {
        mobile: '13800002020',
        code: '246810'
      },
      isLoading: false
    }
  },
  methods: {
    ...mapMutations(['setToken', 'setRefreshToken']),
    // 点击登录
    async onSubmit () {
      this.isLoading = true // 登录按钮样式
      try {
        const res = await loginAPI(this.fromLogin)
        // 登陆成功，跳转页面
        this.$router.push({
          path: '/layout',
          name: 'Layout'
        })
        this.setToken(res.data.data.token)
        this.setRefreshToken(res.data.data.refresh_token)
        Notify({ type: 'success', message: '登录成功啦!' })
        this.isLoading = false
      } catch (err) {
        this.isLoading = false
        Notify({ type: 'warning', message: '登录失败了T.T' })
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
